﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.JsonPatch;
using System.Dynamic;

namespace Demo.Controllers
{
    [ApiController]
    [Route("jsonpatch")]
    public class JsonPatchController : ControllerBase
    {
        public static List<User> _list;
        private readonly ILogger<JsonPatchController> _logger;

        public JsonPatchController(ILogger<JsonPatchController> logger)
        {
            _logger = logger;
            _list = new List<User>();

            _list.Add(new User { Address=new List<Address> { new Address { City="广州", Group="一组" } }, Id=1, Name="jet1" });
            _list.Add(new User { Address = new List<Address> { new Address { City = "深圳", Group = "2组" } }, Id = 2, Name = "jet2" });
            _list.Add(new User { Address = new List<Address> { new Address { City = "西安", Group = "3组" } }, Id = 3, Name = "jet3" });


        }
        [Route("[action]/{id}")]
        [HttpPatch]
        public IActionResult UserOperation(int id, [FromBody] JsonPatchDocument<User> userDoc)
        {
            if (userDoc != null)
            {
                var user =_list.Where(x=>x.Id== id).FirstOrDefault();
                userDoc.ApplyTo(user, ModelState);
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
                 //context.savechange()
                return new ObjectResult(user);
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
       

    }


    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<Address> Address { get; set; }
    }
    public class Address
    {
        public string City { get; set; }
        public string Group { get; set; }
    }
   
}
